'''
This mini-application allows arbitrary commands (global callable objects) to be executed
in the Kharlia environment.
'''

from __future__ import print_function

import argparse

from kharlia import core

def TestRun():
    print('RUNNING TEST FUNCTION')

    app = core.GetApp()
    
    parser = argparse.ArgumentParser(prefix_chars='-+', add_help=False)
    parser.add_argument('++echo', metavar='E', type=int, nargs=1,
                        help='string to echo')

    try:
        args, app.Args = parser.parse_known_args(app.Args)
    except SystemExit as e:
        raise RuntimeError(str(e))

    if args.echo:
        for i in xrange(args.echo[0]):
            print('ECHO!')
    
def TestRun2():
    print('RUNNING TEST FUNCTION 2')

def CmdMain(doexit=True):
    '''
    Executes a global function specified on the command line.
    '''
    core.CTaskletExt.SetCurrentCritical(True)
    app = core.GetApp()

    # Parse our global function names from positional arguments
    parser = argparse.ArgumentParser(prefix_chars='-+', add_help=False)
    parser.add_argument('function', type=str, nargs=1)

    args, app.Args = parser.parse_known_args(app.Args)

    # Exit quietly if nothing specified
    if len(args.function) == 0:
        if doexit:
            app.RequestExit()
        return

    # Resolve the function name to get the callable target
    funcname = args.function[0]
    target = core.FindGlobal(funcname)
    if not callable(target):
        raise TypeError('specified uncallable global: ' + funcname)

    # Perform the command
    target()

    # Shut down the app since this is done
    if doexit:
        app.RequestExit()